package com.zhugang.week05;


/**
 * @program algorithms
 * @description: searchCycleArray
 * @author: chanzhugang
 * @create: 2022/07/06 10:49
 */
public class SearchCycleArray {

    public static void main(String[] args) {
        SearchCycleArray searchCycleArray = new SearchCycleArray();
        int[] nums = new int[]{3, 1};
        int index = searchCycleArray.search(nums, 0);
        System.out.println(index);
    }

    /**
     * 33 搜索旋转排序数组
     *
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        // [4,5,6,7,0,1,2]
        // 二分改造
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[low] <= nums[mid]) {
                // 左侧是有序数组
                if (target >= nums[low] && target < nums[mid]) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            } else {
                // 右侧是有序数组
                if (target > nums[mid] && target <= nums[high]) {
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            }
        }
        return -1;
    }

}